package com.dzmsoft.drools.core.config;

import com.dzmsoft.drools.core.common.Constants;
import com.dzmsoft.drools.core.kie.KieSchedule;
import com.dzmsoft.drools.core.kie.KieTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
@EnableConfigurationProperties(DroolsProperties.class)
public class DroolsAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(name = "kieTemplate")
    public KieTemplate kieTemplate(DroolsProperties droolsProperties){
        KieTemplate kieTemplate = new KieTemplate(droolsProperties.getPath(),droolsProperties.getMode(),droolsProperties.getCacheType());
        String autoUpdate = droolsProperties.getAutoUpdate();
        if (Objects.equals(Constants.OFF, autoUpdate)) {
            // 关闭自动更新
            kieTemplate.setUpdate(999999L);
        } else {
            // 启用自动更新
            kieTemplate.setUpdate(droolsProperties.getUpdate());
        }
        kieTemplate.setListener(droolsProperties.getListener());
        return kieTemplate;
    }

    @Bean
    @ConditionalOnMissingBean(name = "kieSchedule")
    public KieSchedule kieSchedule(KieTemplate kieTemplate) {
        KieSchedule kieSchedule = new KieSchedule(kieTemplate);
        kieSchedule.execute();
        return kieSchedule;
    }

}
